import React, { useState, useMemo } from 'react';
import UploadItem from './UploadItem';
import { UploadPhotoContext } from './context';

import styles from './index.less';

interface PhotoArrayProps {
  type: string;
  title: string;
  url: string;
}

interface UploadPhotoProps {
  action: string;
  photoArray: PhotoArrayProps[];
  onChange(result: {}): void;
}

const UploadPhoto = (props: UploadPhotoProps) => {
  const { action, photoArray, onChange } = props;
  const [uploadForm, setUploadForm] = useState<{}>({});

  useMemo(() => {
    if (Object.values(uploadForm).length) {
      onChange(uploadForm);
    }
  }, [uploadForm]);

  return (
    <UploadPhotoContext.Provider value={{ uploadForm, setUploadForm }}>
      <div className={styles['layout-inline']}>
        {photoArray.length &&
          photoArray.map((item, index) => (
            <UploadItem
              key={index}
              type={item.type}
              action={action}
              title={item.title}
              defaultImageUrl={item.url}
            />
          ))}
      </div>
    </UploadPhotoContext.Provider>
  );
};

export default UploadPhoto;
